const http = require('http');
const url = require('url');
const querystring = require('querystring');

const server = http.createServer((req, res) => {
  const resUrl = url.parse(req.url);
  const params = querystring.parse(resUrl.query);

  switch (resUrl.pathname) {
    case '/user/findById':
      const user = { id: params.id, name: '张三', age: 12 }
      res.writeHead(200, 'ok', {
        'Content-type': 'appliation/json'
      })
      res.write(JSON.stringify({
        status: 200,
        message: '查询成功',
        data: user,
        timestamp: new Date().getTime()
      }))
      break;
    case '/user/save':
      const method = req.method
      if (method == 'POST') {
        let data = [];
        req.on('data', chunk => {
          data += chunk;
        })
        req.on('end', () => {
          console.log(querystring.parse(data.toString()));
        })
        res.writeHead(200, 'OK', {
          'Content-Type': 'application/json'
        })
        res.write(JSON.stringify({
          status: 200,
          message: '保存成功',
          data: null,
          timestamp: new Date().getTime()
        }))
      } else {
        res.writeHead(400, 'Not Method', {
          'Content-Type': 'text/plain'
        })
        res.write('请求方法错误')
      }
      break;
    case '/user/deleteById':

      break;
    default:
      res.writeHead(404, 'Not Found');
      res.write('404 Not Found')
      break;
  }

  res.end();
})
server.listen(3000, '127.0.0.1', () => {
  console.log('localhost:3000服务已开启......');
})